<template>
  <div class="box-border w-full h-full task-setting">
    <div class="flex items-center gap-2 text-lg">
      <span class="text-[#030014]/60">模型管理</span>
      <span class="text-[#030014]/60">></span>
      <span class="text-[#030014]"> {{ isSaving ? '编辑模型' : '查看模型' }}</span>
    </div>
    <div
      class="box-border p-7 pb-10 bg-white/50 rounded-[12px] border_white mt-7 h-[calc(100%-460px)] w-[95%] mx-auto overflow-y-auto scrollbar scrollbar-thumb-gray-300"
    >
      <!-- 基础信息部分 -->
      <div class="flex basic-info">
        <div class="text-[20px] font-bold">基础信息</div>
        <el-form ref="formRef" :model="formData" :rules="basicRules" label-width="120px">
          <el-form-item label="模型名称" prop="model_cname" required>
            <el-input
              v-model="formData.model_cname"
              placeholder="请输入模型名称"
              class="!w-[400px]"
              :readonly="!isSaving"
            />
          </el-form-item>
          <el-form-item label="检测目标" prop="targets" required>
            <div class="flex flex-col gap-2">
              <div v-for="(target, index) in formData.targets" :key="index" class="flex items-start">
                <el-upload
                  class="target-upload"
                  action="#"
                  :auto-upload="false"
                  :show-file-list="false"
                  accept="image/*"
                  @change="(file) => handleTargetImageUpload(file, index)"
                >
                  <div
                    v-if="!target.pic_url"
                    class="w-[50px] h-[50px] border border-dashed border-gray-300 flex items-center justify-center cursor-pointer"
                  >
                    <el-icon><Plus /></el-icon>
                  </div>
                </el-upload>
                <!-- 图片预览和操作区域 -->
                <div v-if="target.pic_url" class="flex flex-col items-center gap-1">
                  <el-image
                    :src="target.pic_url"
                    class="w-[50px] h-[50px] object-cover"
                    :preview-src-list="[target.pic_url]"
                    :initial-index="0"
                    fit="cover"
                    preview-teleported
                  />
                  <!-- 操作按钮 -->
                  <div class="flex items-center gap-4">
                    <template v-if="isSaving">
                      <el-upload
                        action="#"
                        :auto-upload="false"
                        :show-file-list="false"
                        accept="image/*"
                        @change="(file) => handleTargetImageEdit(file, index)"
                      >
                        <el-icon class="text-lg text-gray-500 cursor-pointer hover:text-blue-500"
                          ><EditPen
                        /></el-icon>
                      </el-upload>
                      <el-popconfirm
                        title="确定要删除这张图片吗？"
                        @confirm="removeImg(index)"
                        confirm-button-text="确定"
                        cancel-button-text="取消"
                        :teleported="false"
                      >
                        <template #reference>
                          <el-icon
                            class="mb-1 text-lg text-gray-500 cursor-pointer hover:text-red-500"
                          >
                            <Delete />
                          </el-icon>
                        </template>
                      </el-popconfirm>
                    </template>
                    <template v-else>
                      <el-tooltip content="点击下载图片" placement="top">
                        <el-icon
                          class="!text-xl text-gray-500 cursor-pointer hover:text-blue-500"
                          @click="handleImageDownload(target.pic_url, target.detect_target_cname)"
                        >
                          <Download />
                        </el-icon>
                      </el-tooltip>
                    </template>
                  </div>
                </div>

                <el-input
                  v-model="target.detect_target_cname"
                  placeholder="请输入目标名称"
                  class="!w-[332px] ml-4 mt-4"
                  :readonly="!isSaving"
                />
                <div v-if="isSaving" class="flex items-center gap-2 mt-4 ml-4">
                  <el-popconfirm
                    title="确定要删除这个检测目标吗？"
                    @confirm="removeTarget(index)"
                    confirm-button-text="确定"
                    cancel-button-text="取消"
                  >
                    <template #reference>
                      <div
                        class="flex items-center justify-center bg-white cursor-pointer w-7 h-7 border1 hover:text-red-500"
                      >
                        <el-icon class="text-lg text-gray-500"><Minus /></el-icon>
                      </div>
                    </template>
                  </el-popconfirm>
                  <div
                    v-if="index === formData.targets.length - 1"
                    class="flex items-center justify-center bg-white cursor-pointer w-7 h-7 border1 hover:text-blue-500"
                    @click="addTarget"
                  >
                    <el-icon class="text-lg text-gray-500"><Plus /></el-icon>
                  </div>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 模型文件 -->
    <div
      class="p-7 video-settings w-[95%] mx-auto bg-white/50 rounded-[12px] border_white mt-7 h-[290px] box-border overflow-y-auto scrollbar scrollbar-thumb-gray-300"
    >
      <div class="text-[20px] font-bold">模型文件</div>
      <el-upload
        v-if="isSaving"
        v-model:file-list="fileList"
        class="mt-4 w-[85%] mx-auto"
        drag
        :show-file-list="false"
        :http-request="uploadModel"
        accept=".onnx,.hdf5,.tflite,.pt,.pkl,.bin,.json,.xml,.yaml"
        :multiple="false"
        :disabled="fileList.length >= 1"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="text-[#606266] text-sm mt-2">
          文件扩展名：.onnx .hdf5 .tflite .pt .pkl .bin .json .xml .yaml...
        </div>
      </el-upload>

      <!-- 添加文件列表显示 -->
      <div class="flex flex-wrap gap-4 mt-4">
        <div
          v-for="(file, index) in fileList"
          :key="index"
          class="flex items-center p-3 bg-white border rounded-md"
        >
          <!-- <el-icon class="mr-2 text-2xl text-blue-500"><Document /></el-icon> -->
          <img src="../assets/images/model_file.png" class="w-8 h-8 mr-2" />
          <span class="mr-2">{{ file.name }}</span>
          <el-tooltip v-if="!isSaving" content="点击下载文件" placement="top">
            <el-icon
              class="mr-2 !text-xl text-gray-400 cursor-pointer hover:text-blue-500"
              @click="handleDownload(file)"
            >
              <Download />
            </el-icon>
          </el-tooltip>
          <el-popconfirm
            v-if="isSaving"
            title="确定要删除这个模型文件吗？"
            @confirm="handleRemove(file)"
            confirm-button-text="确定"
            cancel-button-text="取消"
          >
            <template #reference>
              <el-icon class="text-gray-400 cursor-pointer hover:text-red-500">
                <Delete />
              </el-icon>
            </template>
          </el-popconfirm>
        </div>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="action-buttons">
      <el-button type="primary" plain class="!w-[200px] !h-[40px]" @click="handleCancel"
        >退出</el-button
      >
      <el-button type="success" plain class="!w-[200px] !h-[40px]" @click="handleSave">{{
        isSaving ? '保存' : '编辑'
      }}</el-button>
    </div>
  </div>
</template>

<script setup>
import { UploadFilled, Plus, Minus, EditPen, Delete, Download } from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'
import {
  updateModel,
  uploadTargetImage,
  uploadModelFile,
  getModelDetail,
  deleteImageOrModelFile,
} from '@/api/model'
import { watch } from 'vue'
import { ElMessage } from 'element-plus'
import { saveAs } from 'file-saver'

const route = useRoute()
const router = useRouter()

const formData = ref({
  id: '0',
  model_cname: '',
  targets: [
    {
      detect_target_cname: '目标1',
      pic_url: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
    },
  ],
})

// 添加表单引用
const formRef = ref(null)

// 添加验证规则
const basicRules = {
  model_cname: [{ required: true, message: '请输入模型名称', trigger: 'blur' }],
  targets: [
    {
      type: 'array',
      required: true,
      validator: (rule, value, callback) => {
        if (value.some((target) => !target.detect_target_cname || !target.pic_url)) {
          callback(new Error('请上传检测目标的图片和名称'))
        } else {
          callback()
        }
      },
      trigger: 'change',
    },
  ],
}

watch(
  () => route.query,
  async (newId) => {
    if (newId) {
      console.log('🐯 ~ newId:', newId)
      const res = await getModelDetail({ id: newId.id })
      // 处理图片URL
      if (res.data.targets) {
        res.data.targets = res.data.targets.map((item) => ({
          ...item,
          pic_url: item.pic_url ? `${import.meta.env.VITE_IMG_URL}${item.pic_url}` : '',
        }))
      }

      // 处理模型文件名
      if (res.data.model_url) {
        // const fileName = res.data.model_url.split('/').pop() // 提取文件名 'best_int8.onnx'
        fileList.value = [
          {
            name: res.data.original_file_name,
            url: `${res.data.model_url}`,
          },
        ]
      }

      formData.value = res.data
      console.log('🐯 ~ res:', res)
    }
  },
  { immediate: true },
)

// 添加新的目标
const addTarget = () => {
  formData.value.targets.push({ detect_target_cname: '', pic_url: '' })
}

// 删除目标
const removeTarget = async (index) => {
  try {
    if (formData.value.targets.length > 1) {
      // 只有当存在图片 URL 时才调用删除接口
      if (formData.value.targets[index].pic_url) {
        await deleteImageOrModelFile({
          file_url: formData.value.targets[index].pic_url.replace(import.meta.env.VITE_IMG_URL, ''),
        })
      }
      formData.value.targets.splice(index, 1)
      ElMessage.success('检测目标删除成功')
    } else {
      ElMessage.error('至少需要一个检测目标')
    }
  } catch (error) {
    ElMessage.error('检测目标删除失败')
  }
}

const handleCancel = () => {
  // 处理退出逻辑
  router.go(-1)
}

const isSaving = ref(false)
const handleSave = async () => {
  if (!isSaving.value) {
    isSaving.value = true
    return
  }

  try {
    // 验证基础信息表单
    const valid = await formRef.value?.validate().catch(() => false)

    // 模型文件验证
    if (fileList.value.length === 0) {
      ElMessage.error('请上传模型文件')
      return
    }

    if (valid) {
      try {
        // 处理图片URL，移除基础路径
        const processedPics = formData.value.targets.map((pic) => ({
          ...pic,
          pic_url: pic.pic_url.replace(import.meta.env.VITE_IMG_URL, ''),
        }))

        await updateModel({
          id: formData.value.id,
          cname: formData.value.model_cname,
          pics: processedPics,
          original_file_name: fileList.value[0].name,
          model_url: fileList.value[0].url,
        })
        ElMessage.success('模型更新成功')
        router.push('/model_home')
      } catch (error) {
        ElMessage.error('模型更新失败')
      }
    }
  } catch (error) {
    console.error('表单验证失败', error)
  }
}

const handleTargetImageUpload = async (file, index) => {
  console.log('🐯 ~ handleTargetImageUpload ~ index:', formData.value.targets[index])
  console.log('🐯 ~ handleTargetImageUpload ~ file:', file)
  try {
    // 显示上传中的加载状态
    const formData1 = new FormData()
    formData1.append('pic_file', file.raw)

    // 调用上传API
    const res = await uploadTargetImage(formData1)

    // 更新目标图片
    formData.value.targets[index].pic_url = `${import.meta.env.VITE_IMG_URL}${res.data.file_path}`

    ElMessage.success('图片上传成功')
  } catch (error) {
    console.error('图片上传失败:', error)
    ElMessage.error('图片上传失败，请重试')
  }
}

const handleTargetImageEdit = async (file, index) => {
  try {
    // 先删除旧图片
    await deleteImageOrModelFile({
      file_url: formData.value.targets[index].pic_url.replace(import.meta.env.VITE_IMG_URL, ''),
    })

    // 上传新图片
    const formData1 = new FormData()
    formData1.append('pic_file', file.raw)
    const res = await uploadTargetImage(formData1)

    // 更新图片URL
    formData.value.targets[index].pic_url = `${import.meta.env.VITE_IMG_URL}${res.data.file_path}`

    ElMessage.success('图片更新成功')
  } catch (error) {
    console.error('图片更新失败:', error)
    ElMessage.error('图片更新失败，请重试')
  }
}

const removeImg = async (index) => {
  try {
    await deleteImageOrModelFile({
      file_url: formData.value.targets[index].pic_url.replace(import.meta.env.VITE_IMG_URL, ''),
    })
    formData.value.targets[index].pic_url = ''
    ElMessage.success('图片删除成功')
  } catch (error) {
    ElMessage.error('图片删除失败')
  }
}

const fileList = ref([])

const uploadModel = async (file) => {
  try {
    const formData = new FormData()
    formData.append('model_file', file.file)
    // 调用上传API
    const response = await uploadModelFile(formData)
    fileList.value[0].url = response.data.file_path
    fileList.value[0].name = response.data.file_name
    setTimeout(() => {
      const container = document.querySelector('.video-settings')
      if (container) {
        container.scrollTo({
          top: container.scrollHeight,
          behavior: 'smooth',
        })
      }
    }, 100)
    ElMessage.success('模型文件上传成功')
  } catch (error) {
    ElMessage.error('模型文件上传失败')
  }
}

const handleRemove = async (file) => {
  try {
    const index = fileList.value.indexOf(file)
    if (index !== -1) {
      await deleteImageOrModelFile({ file_url: file.url })
      fileList.value.splice(index, 1)
      ElMessage.success('模型文件删除成功')
    }
  } catch (error) {
    ElMessage.error('模型文件删除失败')
  }
}

const handleDownload = async (file) => {
  try {
    saveAs(`${import.meta.env.VITE_IMG_URL}${file.url}`, file.name)
    ElMessage.success('文件下载成功')
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('文件下载失败')
  }
}

const handleImageDownload = async (imageUrl, fileName) => {
  try {
    // 直接使用 file-saver 下载图片
    saveAs(imageUrl, `${fileName}.png`)
    ElMessage.success('图片下载成功')
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('图片下载失败')
  }
}
</script>

<style scoped>
.task-setting {
  padding: 20px 60px;

  .targets-grid {
    display: grid;
    grid-template-columns: repeat(5, 1fr);
    gap: 50px;
    margin-top: 20px;
  }

  .target-item {
    .image-placeholder {
      width: 88px;
      height: 56px;
      background: #f5f7fa;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 10px;

      :deep(.el-image) {
        width: 100%;
        height: 100%;
      }
    }

    .target-name {
      font-size: 14px;
      margin: 8px 0;
      text-align: center;
    }

    .slider-container {
      padding: 0 10px;
    }

    .accuracy-control {
      display: flex;
      justify-content: center;
      margin-top: 10px;
    }
  }

  .action-buttons {
    display: flex;
    justify-content: center;
    gap: 200px;
    margin-top: 40px;
  }

  .image-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
    color: #909399;
  }
}

:deep(.el-form-item__label) {
  font-size: 14px;
}
:deep(.el-upload-dragger) {
  padding: 20px 20px !important;
  background-color: transparent;
}

.border1 {
  border: 1px solid #dcdfe6;
}

:deep(.el-popconfirm) {
  .el-popper.is-light {
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .el-popconfirm__main {
    margin: 8px 0;
    font-size: 14px;
    color: #606266;
  }

  .el-button {
    padding: 8px 16px;
    border-radius: 4px;
    font-size: 13px;
  }

  .el-button--primary {
    background-color: #409eff;
    border-color: #409eff;
    &:hover {
      background-color: #66b1ff;
      border-color: #66b1ff;
    }
  }

  .el-button--default {
    &:hover {
      color: #409eff;
      border-color: #c6e2ff;
      background-color: #ecf5ff;
    }
  }
}
</style>
